package com.library.admin.list;

import java.text.SimpleDateFormat;

import books.storage.service.BookDto;

import com.library.admin.listener.RemoveBookListener;
import com.library.admin.listener.ShowExemplariesNumberListener;
import com.library.admin.service.LibraryService;
import com.vaadin.ui.Button;
import com.vaadin.ui.Table;

public class BookTable extends Table {
	private static final long serialVersionUID = 7299070564286634614L;
	
	public BookTable() {
		init();
	}
	
	public void init() {
		setWidth("100%");
		setImmediate(true);
		setPageLength(0);
		
		addContainerProperty("Nom",						String.class,     	null);
		addContainerProperty("Auteur",					String.class,     	null);
		addContainerProperty("ISBN",					String.class,  		null);
		addContainerProperty("Genre",					String.class,  		null);
		addContainerProperty("Date d'édition",       	String.class, 		null);
		addContainerProperty("Nombre d'exemplaires",	Integer.class,    	null);
		addContainerProperty("Supprimer",        		Button.class, 		null);
		addContainerProperty("+/- des exemplaires",    	Button.class, 		null);

		updateBookTable();
		
		//Creating books container
//		Container bookContainer = new IndexedContainer();
//		bookContainer.addContainerProperty(BOOK_NAME, 	String.class, 		null);
//		bookContainer.addContainerProperty(BOOK, 		AuthorDto.class, 	null);
//		for (AuthorDto author : LibraryService.getServiceAuthor().findAllAuthor()) {
//			Item authorItem = bookContainer.addItem(author.getId());
//			
//			authorItem.getItemProperty(BOOK_NAME).setValue(author.getName());
//			authorItem.getItemProperty(BOOK).setValue(author);
//		}
	}
	
	public void updateBookTable() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		
		for (BookDto book : LibraryService.getServiceBook().findAllBooks()) {
			Button removeButton = new Button("X");
			Button updateExemplariesNumberButton = new Button("+/- des exemplaires");
			
			String itemId = book.getIsbn();
			removeButton.addListener(new RemoveBookListener(this, itemId));
			updateExemplariesNumberButton.addListener(new ShowExemplariesNumberListener(itemId));
			
			String editionDate = dateFormat.format(book.getEditionDate().toGregorianCalendar().getTime());
			
			addItem(new Object[] {book.getTitle(), book.getAuthor().getName(), book.getIsbn(), book.getLiterary().getWording(), editionDate,
					book.getCopiesNumber(), removeButton, updateExemplariesNumberButton}, itemId);
		}
	}
}
